<?php

namespace StarCloud\Library;

use Framework\DiServices\HttpClient;
use Phalcon\Di;
use StarCloud\Library\Exception;

class Tiktok
{
    /* @var $httpClient HttpClient */
    private $httpClient;
    private $cacheClass;
    private $client_key;
    private $client_secret;

    private $redirect_url = 'https://api.doumvip.com/api/tiktok/oauth';

    private $accessToken = 'act.82I2hDLaNNrr5WUhVMX6QAckwj3MLuujLcok74CRIAiw9QDANHM0Z7Sv9VZx!6430.u1';
    public function __construct($config = [])
    {
        $this->httpClient = Di::getDefault()->get('httpClient');
        $this->cacheClass = Di::getDefault()->get('redis');
        $this->client_key = $config['client_key'] ?? "sbawuh35xzyh8lhgvw";
        $this->client_secret = $config['client_secret'] ?? "S3zX2vsktzoNf0OM8L5cj5KN2saQXAT2";
    }

    public function getHeader()
    {
        return [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ];
    }

    public function getRedirectUrl($uid)
    {
        return "https://www.tiktok.com/v2/auth/authorize?client_key={$this->client_key}&scope=video.list,video.publish,video.upload,user.info.basic,user.info.profile&response_type=code&redirect_uri={$this->redirect_url}&state={$uid}";
    }

    public function getOauthToken()
    {
        $url = 'https://open.tiktokapis.com/v2/oauth/token/';
        $body = [
            'client_key' => $this->client_key,
            'client_secret' => $this->client_secret,
            'grant_type' => 'authorization_code',
            'code' => $_GET['code'],
            'redirect_uri' => $this->redirect_url,
        ];
        $header = $this->getHeader();
        $header['Cache-Control'] = 'no-cache';

        $response = $this->httpClient->sendPostRequestUrlEncode($url, $body,$header);

        return json_decode($response->getBody()->getContents(), true);
    }


    public function publishVideo($videoUrl)
    {
        $url = 'https://open.tiktokapis.com/v2/post/publish/video/init/';

        $body = [
            'source_info' => [
                'source' => 'PULL_FROM_URL',
                'video_url' => $videoUrl,
            ],
            "post_info" => [
                "title" => "#novelshort search 94244 read all",
                "video_cover_timestamp_ms" => 1000
            ]
        ];
        $header = $this->getHeader();
        $header['Content-Type'] = 'application/json';
        $header['charset'] = 'UTF-8';
        $header['Authorization'] = 'Bearer ' . $this->accessToken;

        $response = $this->httpClient->sendPostRequest($url, $body,$header);

        return json_decode($response->getBody()->getContents(), true);
    }
    public function uploadVideo($videoUrl)
    {
        $url = "https://open.tiktokapis.com/v2/post/publish/inbox/video/init/";

        $body = [
            'source_info' => [
                'source' => 'PULL_FROM_URL',
                'video_url' => $videoUrl,
            ]
        ];
        $header = $this->getHeader();
        $header['Content-Type'] = 'application/json';
        $header['Authorization'] = 'Bearer ' . $this->accessToken;

        $response = $this->httpClient->sendPostRequest($url, $body,$header);

        return json_decode($response->getBody()->getContents(), true);

    }
    /**
     * 获取
     * @param $uid
     * @return array|bool|float|int|mixed|\stdClass|string|\要转换的数据|null
     */
    public function getOauthQrcode($uid)
    {
        try {
            $url = 'https://open.tiktokapis.com/v2/oauth/get_qrcode/';
            $body = [
                'client_key' => $this->client_key,
                'scope' => 'video.list,video.upload,user.info.basic,user.info.profile',
                'state' => 'uid='.$uid
            ];

            $response = $this->httpClient->sendPostRequestUrlEncode($url, $body, $this->getHeader());

            return json_decode($response->getBody()->getContents(), true);
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            return false;
        }
    }
}